<template>
  <view class="page-container">
    <!-- 使用自定义导航栏组件 -->
    <nav-bar :title="'店铺卡包管理'" />

    <!-- 搜索区域 -->
    <view class="search-bar">
      <view class="search-container">
        <uni-search-bar v-model="searchName" placeholder="输入卡包名称" radius="100" clearButton="auto"
          @confirm="handleSearch" />
        <view class="action-buttons">
          <view class="search-btn" @click="handleSearch">搜索</view>
          <uni-icons class="add-btn" type="plus" size="30" @click="handleCreateCardPackage" />
        </view>
      </view>
    </view>

    <!-- 卡包列表 -->
    <view class="card-package-list" v-if="cardPackages.length">
      <view class="card-package-item" v-for="(item, index) in cardPackages" :key="index"
        @click="handleEditCardPackage(item.package_id)">
        <view class="card-package-info">
          <text class="card-package-name">{{ item.name }}</text>
          <view class="card-package-meta">
            <uni-tag :text="item.card_type === 'per_use' ? '次卡' : '综合卡'"
              :type="item.card_type === 'per_use' ? 'success' : 'warning'" size="small" />
            <text class="amount-text">
              充值: {{ item.recharge_amount || 0 }}元
            </text>
            <text class="amount-text">
              {{ item.card_type === 'per_use' ? '次数' : '赠送' }}:
              {{ item.card_type === 'per_use' ? item.total_amount : (item.gift_amount || 0) }}
              {{ item.card_type === 'per_use' ? '次' : '元' }}
            </text>
          </view>
          <view class="card-package-meta">
            <text class="amount-text">
              销售提成: {{ item.commission_rate * 100 || 0 }}%
            </text>
            <text class="amount-text">
              客户打折: {{ (item.discount_rate * 10).toFixed(1) == 10 ? '不打折' : ((item.discount_rate * 10).toFixed(1) + '折')
              }}
            </text>
          </view>
          <text class="expiry-date" v-if="item.expiry_date">
            有效期至: {{ Util.formatDate(item.expiry_date) }}
          </text>
        </view>
        <view class="detail-link">
          <uni-icons type="arrowright" size="20" color="#999"></uni-icons>
        </view>
      </view>
    </view>

    <view v-else class="empty-tip">
      <text>暂无卡包信息</text>
    </view>
  </view>
</template>

<script>
// 导入自定义导航栏组件
import NavBar from '@/components/nav-bar/nav-bar.vue'

import cardPackage from '@/utils/card_package.js';
import Util from '@/utils/util.js';

export default {
  data() {
    return {
      Util,
      searchName: '',
      cardPackages: [],
      storeId: '',
      managerId: ''
    };
  },
  onLoad(options) {
    this.storeId = options.store_id || '';
    this.managerId = options.manager_id || '';
    this.fetchCardPackages();

    // 添加监听refreshCardPackageList事件
    uni.$on('refreshCardPackageList', this.fetchCardPackages);
  },
  onUnload() {
    // 移除事件监听
    uni.$off('refreshCardPackageList', this.fetchCardPackages);
  },
  methods: {
    async fetchCardPackages() {
      try {
        const params = {
          store_id: this.storeId
        };
        if (this.searchName) {
          params.name = this.searchName;
        }
        const res = await cardPackage.getList(params);
        this.cardPackages = res;
      } catch (error) {
        uni.showToast({
          title: '数据加载失败',
          icon: 'none'
        });
      }
    },
    handleSearch() {
      this.fetchCardPackages();
    },
    async handleCreateCardPackage() {
      try {
        // 获取当前用户信息
        const userInfo = Util.getUserInfo();
        // 权限判断
        console.log(userInfo.user_id, this.managerId)
        if (!(userInfo.role == 'admin' || userInfo.user_id == this.managerId)) {
          uni.showToast({
            title: '非店主没有管理权限添加卡包',
            icon: 'none'
          });
          return;
        }

        // 有权限则跳转
        uni.navigateTo({
          url: `/pages/card_package/edit?store_id=${this.storeId}`
        });
      } catch (error) {
        uni.showToast({
          title: '权限验证失败',
          icon: 'none'
        });
      }
    },
    handleEditCardPackage(packageId) {
      try {
        // 获取当前用户信息
        const userInfo = Util.getUserInfo();
        // 权限判断
        if (userInfo.role !== 'admin' && userInfo.user_id !== this.managerId) {
          uni.showToast({
            title: '非店主没有管理权限添加卡包',
            icon: 'none'
          });
          return;
        }

        // 有权限则跳转
        uni.navigateTo({
          url: `/pages/card_package/edit?package_id=${packageId}&store_id=${this.storeId}`
        });
      } catch (error) {
        uni.showToast({
          title: '权限验证失败',
          icon: 'none'
        });
      }

    }
  }
}
</script>

<style lang="scss">
@import '@/uni.scss';

/* 卡包列表样式 */
.card-package-list {
  margin-top: 30rpx;
}

.card-package-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.card-package-info {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.card-package-name {
  font-size: 36rpx;
  color: $uni-main-color;
  font-weight: bold;
}

.card-package-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.amount-text {
  font-size: 28rpx;
  color: $uni-text-color-grey;
  flex: 1;
  min-width: 200rpx;
}

.expiry-date {
  font-size: 28rpx;
  color: $uni-text-color-grey;
  margin-top: 10rpx;
}

.detail-link {
  display: flex;
  justify-content: flex-end;
  margin-top: 20rpx;
}

.empty-tip {
  text-align: center;
  padding: 40rpx;
  color: $uni-text-color-grey;
}
</style>